package edu.beyond.employment.commom.util;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import edu.beyond.employment.company.entity.CompanyEntity;
import edu.beyond.employment.talent.entity.TalentEntity;

public class AppUtil {
	private static Logger LOG = Logger.getLogger(AppUtil.class);

	private AppUtil() {

	}

	/**
	 * 判断talent是否有登录
	 */
	public static boolean isLoggin(HttpServletRequest request) {
		if (request.getSession().getAttribute("talent") == null) {
			return false;
		}
		return true;
	}

	/**
	 * 获取放到Session里面的talent对象
	 */
	public static TalentEntity getTalent(HttpServletRequest request, HttpServletResponse response) {
		if (request.getSession().getAttribute("talent") == null) {
			request.setAttribute("sessionClosed", "会话已经关闭");
			try {
				request.getRequestDispatcher("static/talent/talent-login.jsp").forward(request, response);
			} catch (ServletException | IOException e) {
				Util.e(LOG, e.getMessage(), e);
			}
			throw new RuntimeException("会话已经关闭！获取Session中的内容失败");
		} else {
			return (TalentEntity) request.getSession().getAttribute("talent");
		}
	}

	/**
	 * 获取放到Session里面的Talent的id
	 * 
	 * @param request
	 * @return
	 */
	public static int getTalentId(HttpServletRequest request, HttpServletResponse response) {
		return getTalent(request, response).getId();
	}

	/**
	 * 获取放到Session里面的Company对象
	 *
	 * @param request
	 * @return
	 */
	public static CompanyEntity getCompany(HttpServletRequest request, HttpServletResponse response) {
		if (request.getSession().getAttribute("company") == null) {
			request.setAttribute("sessionClosed", "会话已经关闭！");
			try {
				request.getRequestDispatcher("static/company/company-login.jsp").forward(request, response);
			} catch (ServletException | IOException e) {
				Util.e(LOG, e.getMessage(), e);
			}
			throw new RuntimeException("会话已经关闭！获取Session中的内容失败");
		} else {
			return (CompanyEntity) request.getSession().getAttribute("company");
		}
	}

	/**
	 * 获取放到Session里面的Company的id
	 *
	 * @param request
	 * @return
	 */
	public static int getCompanyId(HttpServletRequest request, HttpServletResponse response) {
		return getCompany(request, response).getId();
	}

}
